﻿using GMap.NET.MapProviders;
using GMap.NET;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GMap.NET.Projections;
using GMap.NET.WindowsForms;

namespace AgCIM.Tools.DP.AgControls
{
    public class LocalTileProvider : GMapProvider
    {
        public static readonly LocalTileProvider Instance;

        private readonly string _tilePath;
        private System.Guid m_id = Guid.NewGuid();
        private GMapProvider[] _overlays;

        public LocalTileProvider(string tilePath = "tiles")
        {
            _tilePath = tilePath;
            MaxZoom = 18; // 设置最大缩放级别
            MinZoom = 0;  // 设置最小缩放级别

        }

        public override Guid Id => m_id;

        public override string Name => _tilePath;

        public override PureProjection Projection
        {
            get
            {
                return MercatorProjection.Instance;
            }
        }

        public override GMapProvider[] Overlays
        {
            get
            {
                if (_overlays == null)
                {
                    _overlays = new GMapProvider[] { this };
                }

                return _overlays;
            }
        }

        public override void OnInitialized()
        {
            base.OnInitialized();
        }
        public override PureImage GetTileImage(GPoint pos, int zoom)
        {
            var y = Math.Pow(2, zoom);
            string filePath = Path.Combine(
                _tilePath,
                zoom.ToString(),
                pos.X.ToString(),
                (y - pos.Y - 1) + ".png"); // 或.jpg根据实际格式

            if (File.Exists(filePath))
            {
                return new LocalTifFileGMapImageProxy(filePath);
            }

            return null;
        }
    }

    public class LocalTifFileGMapImageProxy : GMapImage
    {
        private readonly string _filePath;

        public LocalTifFileGMapImageProxy(string filePath)
        {
            try
            {
                _filePath = filePath;

                var image = System.Drawing.Image.FromFile(filePath);

                MemoryStream ms = new MemoryStream();
                image.Save(ms, image.RawFormat);
                ms.Position = 0;
                this.Data = ms;

                this.Img = image;
            }
            catch (Exception ex)
            {
                //File.Delete(filePath);
            }
        }

        public override void Dispose()
        {
            this.Data.Dispose();
        }
    }
}
